<template>
  <!-- 标题 -->
  <van-nav-bar
    title="用户管理"
    left-text=""
    right-text=""
  />

  <!-- 添加用户的表单 -->
  <div class="form-section">
    <van-field v-model="newUser.name" placeholder="请输入姓名" />
    <van-field v-model="newUser.level" placeholder="请输入等级" />
    <van-button type="primary" @click="addUser">添加用户</van-button>
  </div>

  <!-- 用户列表 -->
  <div class="userlist-section">
    <table class="van-table" border style="width: 100%">
      <thead>
        <tr>
          <th>编号</th>
          <th>姓名</th>
          <th>等级</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in userlist" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.level }}</td>
          <td>
            <router-link :to="'/home/users/' + item.id">详情  </router-link>
            <van-button plain size="small" @click.stop="editUser(item)">修改</van-button>
            <van-button plain size="small" type="danger" @click.stop="deleteUser(item.id)">删除</van-button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import 'vant/lib/index.css'; // 引入 Vant CSS
import { NavBar, Field, Button, List, Cell, Icon } from 'vant'; // 引入 Vant 组件

// 初始化函数从 localStorage 读取数据
const initializeUserlist = () => {
  const storedUsers = localStorage.getItem('users')
  return storedUsers ? JSON.parse(storedUsers) : [
    { id: '1', name: '小明', level: '一级客户' },
    { id: '2', name: '小红', level: '二级客户' },
    { id: '3', name: '小兰', level: '三级客户' },
    { id: '4', name: '小芳', level: '四级客户' },
  ]
}

const userlist = ref(initializeUserlist())
const newUser = ref({ name: '', level: '' })

// 每当 userlist 发生变化，都将其保存到 localStorage
watch(userlist, (newVal) => {
  localStorage.setItem('users', JSON.stringify(newVal))
}, { deep: true })

const addUser = () => {
  const id = (userlist.value.length + 1).toString()  // generate a new id
  userlist.value.push({
    id,
    ...newUser.value
  })
  newUser.value = { name: '', level: '' } // reset the form
}

const deleteUser = (id) => {
  userlist.value = userlist.value.filter(user => user.id !== id)
}

const editUser = (item) => {
  const name = prompt('输入新的姓名', item.name)
  const level = prompt('输入新的等级', item.level)
  if (name) item.name = name
  if (level) item.level = level
}
</script>

<style scoped>
.form-section {
  padding: 16px;
  background-color: #f7f8fa;
}

.userlist-section {
  margin-top: 20px;
}
.van-button{
	margin: 0 4px;
}
</style>


